package dbinit;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import core.role.model.BasicRoleRules;
import core.util.HibernateCoreUtil;

public class InitBasicRoleRules {
	public static BasicRoleRules getBasicRoleRulesByUUID(Long uuid)
	{
		BasicRoleRules brr = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
			transaction = session.beginTransaction();
			brr = (BasicRoleRules) session.get(BasicRoleRules.class, uuid);
			transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return brr ;
	}
	public static BasicRoleRules getBasicRoleRulesByName(String name)
	{
		BasicRoleRules brr = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
		    if(name != null || name.trim().length() != 0)
		    {
		    	name = name.trim();
		    	brr = (BasicRoleRules)session.createCriteria(BasicRoleRules.class).add(Restrictions.eq("roleRule", name)).uniqueResult();
		    }
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return brr ;
	}
	public static Long doinit(String roleRuleName, String description,String permissiontype)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		BasicRoleRules basicrolerules = getBasicRoleRulesByName(roleRuleName);
		if(basicrolerules == null)
		{
			basicrolerules = new BasicRoleRules();
		}
		basicrolerules.setRoleRule(roleRuleName);
		basicrolerules.setDescription(description);
		Long uuid = null;
		try
		{
			transaction = session.beginTransaction();
			basicrolerules = (BasicRoleRules)session.merge(basicrolerules);
			uuid = basicrolerules.getUuid();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return uuid ;
	}

}
